package com.thermofisher.dsc.amanda.security.service;

import com.thermofisher.dsc.amanda.auth.mapper.UserMapper;
import com.thermofisher.dsc.amanda.model.po.auth.User;
import com.thermofisher.dsc.amanda.security.model.SecurityUserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * Created by wenjie.yang on 1/3/2019.
 */
@Component
public class SecurityUserDetailsService implements UserDetailsService {

  @Autowired
  private UserMapper userMapper;

  @Override
  public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    User record = new User();
    record.setUserName(userName);
    User user = userMapper.selectOne(record);

    if (null == user) {
      throw new UsernameNotFoundException("用户名或密码错误");
    }
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
    authorities.add(simpleGrantedAuthority);
    List<String> permissions = userMapper.getUserPermissionsCode(user.getId());
    SimpleGrantedAuthority authority;
    for (String permission : permissions) {
      authority = new SimpleGrantedAuthority(permission);
      authorities.add(authority);
    }
    //创建UserDetails对象
    SecurityUserDetails userDetails = new SecurityUserDetails(user.getId().intValue(),
        user.getUserName(), user.getPassword(), true, authorities);
    userDetails.setEmail(user.getEmailAddress());
    userDetails.setPhone(user.getPhoneNumber());
    return userDetails;
  }
}
